package com.controller.agent;

import com.core.BaseBiz;
import com.core.Result;
import com.core.ResultGenerator;
import com.entity.cond.BaseCond;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import static org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors;

/**
 * Created by asan on 2017-09-05.
 */
public class BaseController<T> {
    protected final Log logger = LogFactory.getLog(getClass());
    @Autowired
    protected BaseBiz<T> baseBiz;
    private Class<T> entityClass;

    public BaseController() {
        Type genType = getClass().getGenericSuperclass();
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        entityClass = (Class) params[0];
    }

    /**
     * 得到request对象
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    /**
     * 得到response对象
     */
    public HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }


    public void SetCondition(T t, Condition cond) throws BeansException {
        Example.Criteria criteria = cond.createCriteria();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(entityClass);
        for (PropertyDescriptor targetPd : targetPds) {
            if (targetPd != null && targetPd.getWriteMethod() != null) {
                try {
                    Method readMethod = targetPd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(t);
                    // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
                    if (value != null && value != "") {
                        criteria.andEqualTo(targetPd.getName(), value);
                    }
                } catch (Throwable ex) {
                }
            }

        }
    }

    /**
     * 资源的权限（URl级别）
     *
     * @param type 资源类别(优化速度)
     * @return
     */
    protected boolean doSecurityIntercept(String type) {
        try {
            String servletPath = getRequest().getServletPath();
            servletPath = StringUtils.substringBeforeLast(servletPath, ".");// 去掉后面的后缀
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return false;
    }

    /**
     * 获得一个对象
     */
    @RequestMapping(value = "getById")
    @ResponseBody
    public Result getById(@RequestParam Integer id) {
        return ResultGenerator.genSuccessResult(baseBiz.findById(id));
    }

    /**
     * 查找一批对象
     */
    @RequestMapping(value = "find")
    @ResponseBody
    public Result find(T t) {
        Condition cond = new Condition(entityClass);
        SetCondition(t, cond);
        return ResultGenerator.genSuccessResult(baseBiz.findByCondition(cond));
    }

    /**
     * 查找分页后的grid
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public Result list(BaseCond baseCond, T t) {
        PageHelper.startPage(baseCond.getPageNum(), baseCond.getPageSize(), false);
        PageHelper.orderBy(baseCond.getOrderBy());
        Condition cond = new Condition(entityClass);
        SetCondition(t, cond);
        List<T> list = baseBiz.findByCondition(cond);
        Integer total = baseBiz.countByCond(cond);
        return ResultGenerator.genSuccessResult(list, total);
    }

    /**
     * 新增一个对象
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Result add(T o) {
        if (o != null) {
            baseBiz.save(o);
            return ResultGenerator.genSuccessResult(o);
        }
        return ResultGenerator.genFailResult("操作失败");
    }

    /**
     * 更新一个对象
     */
    @RequestMapping(value = "update")
    @ResponseBody
    public Result update(T objdata) {
        if (objdata != null) {
            baseBiz.update(objdata);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("操作失败");
    }

    /**
     * 删除一个对象
     */
    @RequestMapping(value = "del", method = RequestMethod.POST)
    @ResponseBody
    public Result del(@RequestParam Integer id) {
        if (id != null) {
            baseBiz.deleteById(id);
            return ResultGenerator.genSuccessResult();
        }
        return ResultGenerator.genFailResult("操作失败");
    }
}
